package com.cskaoyan.market.admin.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.cskaoyan.market.admin.service.AdminTopicService;
import com.cskaoyan.market.admin.service.impl.AdminTopicServiceImpl;
import com.cskaoyan.market.db.domain.MarketTopic;
import com.cskaoyan.market.util.HttpUtil;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 专题管理控制层
 *
 * @author BlackFlame33
 * @date 2023/03/22
 **/
@WebServlet("/admin/topic/*")
public class AdminTopicController extends HttpServlet {
    private AdminTopicService adminTopicService = new AdminTopicServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/topic", "");
        switch (op) {
            case "/list":
                getTopicList(req, resp);
                break;
            case "/read":
                readTopic(req, resp);
                break;
            default:
                resp.setStatus(404);
        }
    }

    private void getTopicList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        // 校验
        if (StringUtils.isEmpty(pageParam) || StringUtils.isEmpty(limitParam)) {
            // 这两个参数都要求必须是有的
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        // 关于sort、order正常情况下应该是需要有的，如果没有传过来，那么设置一个默认值
        if (StringUtils.isEmpty(sort)) {
            sort = "add_time";
        }
        if (StringUtils.isEmpty(order)) {
            order = "desc";
        }
        int page = 0;
        int limit = 0;
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
        } catch (Exception e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        List<MarketTopic> list = adminTopicService.getTopicList(page, limit, sort, order);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(list)));
    }

    private void readTopic(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String topicIdParam = req.getParameter("id");
        int topicId;
        try {
            topicId = Integer.parseInt(topicIdParam);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgumentValue()));
            return;
        }
        Map<String, Object> data = adminTopicService.readTopic(topicId);
        if (data == null) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail()));
        } else {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(data)));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/topic", "");
        switch (op) {
            case "/create":
                createTopic(req, resp);
                break;
            case "/update":
                updateTopic(req, resp);
                break;
            case "/delete":
                deleteTopic(req, resp);
                break;
            default:
                resp.setStatus(404);
        }
    }

    private void createTopic(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        List<Integer> goods = JacksonUtil.parseIntegerList(requestBody, "goods");
        String title = JacksonUtil.parseString(requestBody, "title");
        String subtitle = JacksonUtil.parseString(requestBody, "subtitle");
        String picUrl = JacksonUtil.parseString(requestBody, "picUrl");
        String content = JacksonUtil.parseString(requestBody, "content");
        String priceParam = JacksonUtil.parseString(requestBody, "price");
        String readCount = JacksonUtil.parseString(requestBody, "readCount");
        int price = 0;
        try {
            price = Integer.parseInt(priceParam);
        } catch (Exception e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(402, "参数值不对")));
            return;
        }
        MarketTopic data = adminTopicService.createTopic(goods.toArray(new Integer[]{}), title, subtitle, picUrl,
                content, price, readCount);
        if (data == null) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail()));
        } else {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(data)));
        }
    }

    private void updateTopic(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        MarketTopic marketTopic = null;
        try {
            marketTopic = objectMapper.readValue(requestBody, MarketTopic.class);
        } catch (Exception e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(402, "参数值不对")));
            return;
        }
        MarketTopic data = adminTopicService.updateTopic(marketTopic);
        if (data == null) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail()));
        } else {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(data)));
        }
    }

    private void deleteTopic(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        MarketTopic marketTopic = objectMapper.readValue(requestBody, MarketTopic.class);
        int code = adminTopicService.deleteTopic(marketTopic);
        if (code != 1) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail()));
        } else {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));
        }
    }
}